package com.eco.fanliapp.job.goodsfree;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.GoodsFreeMapper;
import com.eco.fanliapp.dao.SyChannelGoodsMapper;
import com.eco.fanliapp.dao.SyTljGoodsfreeMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 从大淘客拉取免单商品
 *
 * @date 2019-11-25
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DTKGoodsFreeTask implements Job, Serializable {

    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;


    private static final Logger log = LoggerFactory.getLogger(DTKGoodsFreeTask.class);

    public DTKGoodsFreeTask() {
    }

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行免单商品定时拉取任务-DTKGoodsFreeTask：executeCount=" + executeCount + "--startTime=" + startTime);
        //从大淘客拉取免单商品
        //跳过 教材、教程、试题
        String pageId = "1";
        String pageSize = "100";
        while (true) {
            try {
                String result = daTaoKeItemInfoService.getGoodsFreeList(pageSize, pageId.toString());
                result = JSONObject.parseObject(result).getString("data");
                if (result == null) {
                    break;
                }
                String pageid = JSONObject.parseObject(result).getString("pageId");
                JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
                List<DTKResponse.DataBean> dtkResponse = JsonUtils.getJsonToList(array.toJSONString(), DTKResponse.DataBean.class);
                if (dtkResponse == null || dtkResponse.size() <= 0) {
                    log.info("添加免单商品失败null   0 0 2 * * ?");
                    break;
                }
                AppCompany com = userCashschemeService.findCompanyAll();
                for (DTKResponse.DataBean dataBean : dtkResponse) {
                    if (dataBean != null && Double.valueOf(dataBean.getActualPrice()) <= 7D && Double.valueOf(dataBean.getCommissionRate()) >= 70D) {
                        if (dataBean.getTitle().contains("年级") || dataBean.getTitle().contains("编程") || dataBean.getTitle().contains("教学") || dataBean.getTitle().contains("试题") || dataBean.getTitle().contains("微信") || dataBean.getTitle().contains("流量")
                                || dataBean.getTitle().contains("作文") || dataBean.getTitle().contains("教程") || dataBean.getTitle().contains("注册") || dataBean.getTitle().contains("视频") || dataBean.getTitle().contains("考试")
                                || dataBean.getTitle().contains("基础") || dataBean.getTitle().contains("拼音") || dataBean.getTitle().contains("试卷")) {
                            continue;
                        }
                        AppGoods goods = HDKUtils.getAppGoodsFromDTK(dataBean);
                        goods = iAppGoodsService.getMoneyInfoByGoodsId(com, goods);
                        //判断是否最终金额小于0
                        BigDecimal itemendprice = new BigDecimal(goods.getItemendprice() == null ? 0d : goods.getItemendprice());
                        BigDecimal tkMoney = new BigDecimal(goods.getTkmoney() == null ? "0" : goods.getTkmoney());
                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                            continue;
                        }
                        if (goods.getItemendprice() > 7D || goods.getItemendprice() < 5D) {
                            continue;
                        }
                        goods.setItemTop(3);
                        goods.setTaobaoImage(goods.getTaobaoImage() == null ? goods.getItempic() : goods.getTaobaoImage().replace(" ", ""));
                        goods.setCreateTime(DateUtils.getNowTimestamp());
                        goods.setUpdateTime(DateUtils.getNowTimestamp());

                        //判断商品是否存在淘礼金,高佣中
                        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(Long.valueOf(goods.getItemid()));
                        SyTljGoodsfree syTljGoodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(goods.getItemid()));
                        if (syTljGoodsfree != null && DateUtils.date2Strday(syTljGoodsfree.getUpdateTime()).equals(DateUtils.date2Strday(new Date())) || syChannelGoods != null) {
                            continue;
                        }
                        Integer count = goodsFreeMapper.countGoodsFree();
                        if (count < 30) {
                            //根据商品id查询商品是否存在
                            Integer appGoodsNum = appGoodsMapper.selectCountByItemId(goods.getItemid());
                            if (appGoodsNum > 0) {
                                int i = appGoodsMapper.updateGoodsByItemId(goods.getItemid(), goods.getRecommend() == null ? 0 : goods.getRecommend(), goods.getActivityType(), goods.getStartTime(), goods.getEndTime());
                                if (i > 0) {
                                    appGoodsMapper.updateAppGoods(goods);
                                }
                            } else {
                                int i = appGoodsMapper.insertAppGoods(goods);
                                if (i > 0) {
                                    log.info("添加商品成功   0 0 2 * * ?");
                                }
                            }

                            //保存到免单表
                            GoodsFree goodsFree = new GoodsFree();
                            goodsFree.setGoodsId(goods.getItemid());
                            goodsFree.setGoodsTitle(goods.getItemshorttitle());
                            goodsFree.setBeginTime(DateFormatUtils.dateToLong(new Date()));
                            goodsFree.setEndTime(DateFormatUtils.dateToLong(DateFormatUtils.addDate(new Date(), 3)));
                            goodsFree.setFixedAmount(goods.getItemendprice());
                            goodsFree.setGoodsPictureUrl(goods.getItempic());
                            goodsFree.setNumber(100);

                            int i = addGoodsFreeByDTK(goodsFree);
                            if (i == 1) {
                                log.info("添加商品成功   0 0 2 * * ?");
                                continue;
                            }
                        } else {
                            List<String> ids = goodsFreeMapper.selectGoodsFreeByLimit(count - 30);
                            if (ids.size() > 0) {
                                goodsFreeMapper.deleteBatchIds(ids);
                            } else {
                                break;
                            }

                        }
                    }
                }
                pageId = pageid;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取商品列表错误***结束");
                break;
            }
        }


        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行免单商品拉取任务-DTKGoodsFreeTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    public int addGoodsFreeByDTK(GoodsFree goodsFreeInfo) {
        //默认总公司
        goodsFreeInfo.setCompanyId(1);
        //默认平台淘宝
        goodsFreeInfo.setGoodsPlatform(1);
        if (!RegUtils.isNumeric(goodsFreeInfo.getGoodsId())) {
            log.info("商品id格式不正确", goodsFreeInfo.getGoodsId());
            return 0;
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("goodsId", goodsFreeInfo.getGoodsId());
            map.put("companyId", 1);
            map.put("goodsStatus", 2);
            int size = goodsFreeMapper.selectByGoodsIds(map).size();
            if (size > 0) {
                log.info("该商品已经存在(且为激活状态)，请选择其他它商品", goodsFreeInfo.getGoodsId());
                log.info("********:" + goodsFreeInfo.getGoodsId());
                return 0;
            }

            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goodsFreeInfo.getGoodsId());
            if (appGoods != null) {
                GoodsFree goodsFree = new GoodsFree();
                goodsFree.setGoodsId(goodsFreeInfo.getGoodsId());
                goodsFree.setGoodsName(goodsFreeInfo.getGoodsName() == null ? appGoods.getItemshorttitle() : goodsFreeInfo.getGoodsName());
                goodsFree.setGoodsPlatform(goodsFreeInfo.getGoodsPlatform());
                goodsFree.setFixedAmount(goodsFreeInfo.getFixedAmount());
                Long longEndTime = goodsFreeInfo.getEndTime();
                goodsFree.setEndTime(longEndTime);
                Long longBeginTime = DateFormatUtils.dateToLong(new Date());
                goodsFree.setBeginTime(longBeginTime);
                goodsFree.setGoodsPictureUrl(appGoods.getItempic());
                goodsFree.setGoodsTitle(appGoods.getItemtitle());
                if (longEndTime > System.currentTimeMillis()) {
                    goodsFree.setGoodsStatus(2);
                } else {
                    goodsFree.setGoodsStatus(1);
                }
                goodsFree.setPrintUrl(goodsFreeInfo.getPrintUrl() == null ? appGoods.getItempic() : goodsFreeInfo.getPrintUrl());
                goodsFree.setNumber(goodsFreeInfo.getNumber());
                goodsFree.setCompanyId(goodsFreeInfo.getCompanyId());
                int insert = goodsFreeMapper.insertSelective(goodsFree);
                appGoods.setItemTop(3);
                appGoods.setFqcat("0");
                appGoods.setTkmoney(String.valueOf(goodsFreeInfo.getFixedAmount()));
                appGoods.setItempic(goodsFreeInfo.getPrintUrl());
                appGoods.setItemtitle(goodsFreeInfo.getGoodsName());
                appGoods.setItemshorttitle(goodsFreeInfo.getGoodsName());
                appGoodsMapper.updateAppGoods(appGoods);
                if (insert == 1) {
                    log.info("数据增加成功");
                    return 1;
                } else {
                    log.info("数据增加失败");
                    return 0;
                }
            }
        }
        return 0;
    }
}
